package com.wx.activitys.admin.controller;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.sd4324530.fastweixin.api.response.GetUserInfoResponse;
import com.wx.activitys.base.utils.Common;
import com.wx.activitys.base.utils.WebUtil;
import com.wx.activitys.drp.JsonResult;
import com.wx.activitys.drp.EnumUtils.FeedbackState;
import com.wx.activitys.drp.model.BFeedback;
import com.wx.activitys.drp.service.BFeedbackService;
import sun.misc.BASE64Decoder;

@Controller
@RequestMapping(value="/feedback")
public class FeedbackController {
	
	@Autowired
	private BFeedbackService bFeedbackService;
	
	@RequestMapping(value = "list.html", method = RequestMethod.GET)
	public String list(Model model, HttpServletRequest request) {
		BFeedback entity = new BFeedback();
		entity.getMap().put("pageSize", 15);
		entity.getMap().put("pageIndex", 0);
		Integer count = bFeedbackService.selectCount(entity);
		entity.getMap().put("sort","state");
		List<BFeedback> BFeedbacks= bFeedbackService.queryPageList(entity);
		int pageSum = count % 15 == 0 ? count / 15 : (count / 15) + 1;
		model.addAttribute("BFeedbacks", BFeedbacks);
		model.addAttribute("count", count);
		model.addAttribute("pageSum", pageSum);
		model.addAttribute("pageNo", 1);
		return "admin/feedbackManager/list";
	}
	
	@RequestMapping(value = "detail.html", method = RequestMethod.GET)
	public String detail(Model model, HttpServletRequest request) {
		int id = WebUtil.getInt(request, "id", 1);
		BFeedback entity = new BFeedback();
		entity.setId(id);
		List<BFeedback> bFeedback = bFeedbackService.selectByEntity(entity);
		String imgUrl = bFeedback.get(0).getImgUrl();
		if(StringUtils.isNotBlank(imgUrl)){
			String[] imgUrl1 = imgUrl.split(",");
			model.addAttribute("imgUrl", imgUrl1);
		}
		model.addAttribute("bFeedback", bFeedback.get(0));
		return "admin/feedbackManager/detail";
	}

	@RequestMapping(value = "newPage.html", method = RequestMethod.POST)
	@ResponseBody
	public Object newPage(Model model, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<>();
		BFeedback entity = new BFeedback();
		int pageNo = WebUtil.getInt(request, "pageNo", 1);
		int begin = (pageNo - 1) * 15;
		entity.getMap().put("pageSize", 15);
		entity.getMap().put("pageIndex", begin);
		Integer count = bFeedbackService.selectCount(entity);
		entity.getMap().put("sort","state");
		List<BFeedback> BFeedbacks = bFeedbackService.queryPageList(entity);
		int pageSum = count % 15 == 0 ? count / 15 : (count / 15) + 1;
		map.put("BFeedbacks", BFeedbacks);
		map.put("count", count);
		map.put("pageSum", pageSum);
		map.put("pageNo", pageNo);
		return map;
	}
	
	@RequestMapping(value = "updateState.html", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult update(Model model, HttpServletRequest request,BFeedback bFeedback) { 
		int flag = bFeedbackService.update(bFeedback);
		if(flag>0){
			return JsonResult.success("操作成功", flag);
		}else{
			return JsonResult.fail("操作失败", flag);
		}
	}
	
	
	@RequestMapping(value = "insertFeedback.html", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult insert(Model model, HttpServletRequest request,BFeedback bFeedback,@RequestParam("imgStr") String[] imgStr) {
		GetUserInfoResponse userInfo = ((GetUserInfoResponse) request.getSession().getAttribute("userInfo"));
		if(userInfo!=null){
			String path = Common.IMG_SAVE_BASEPATH+"feedback/";
			if(imgStr.length>0){
				String ingPaths="";
				for (int i = 0; i < imgStr.length; i++) {
					if(!imgStr[i].equals("[]")){
						String ingPath = GenerateImage(imgStr[i], path);
						ingPaths+=ingPath+",";
				   }
				}
				bFeedback.setImgUrl(ingPaths);
			}
			bFeedback.setOpenid(userInfo.getOpenid());
			bFeedback.setCreateTime(new Date());
			bFeedback.setState(FeedbackState.待解决.getValue());
			int flag = bFeedbackService.insert(bFeedback);
		if(flag>0){
			return JsonResult.success("操作成功", flag);
		}else{
			return JsonResult.fail("操作失败", flag);
		}
		}else{
			return JsonResult.fail("操作失败", "");
		}
	}
	
	public static String GenerateImage(String imgStr, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片
		if (imgStr == null) // 图像数据为空
			return null;
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			// Base64解码
			byte[] bytes = decoder.decodeBuffer(imgStr);
			for (int i = 0; i < bytes.length; ++i) {
				if (bytes[i] < 0) {// 调整异常数据
					bytes[i] += 256;
				}
			}
			//File file1 = new File(imgFilePath);
			//file1.mkdirs();
			String fileName = Common.generateUUID() + ".jpg";
			String file = imgFilePath + fileName;
			// 生成jpeg图片
			OutputStream out = new FileOutputStream(file);
			out.write(bytes);
			out.flush();
			out.close();
			 return "feedback/" + fileName;
		  } catch (Exception e) {
			 return null;
		}
	}

}
